/*
 * CloudBank Mobile Knowledge Sharing for Language Learners
 * Supported by the JISC Rapid Innovation Programme #jiscri
 *
 * Copyright (C) 2010 University of Brighton
 *
 * Licensed under the GNU General Public License v3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/gpl.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package uk.ac.brighton.itrg.cloudbank;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;


public class ActivityMain extends Activity implements OnClickListener
{
	private static final String TAG = ActivityMain.class.getSimpleName();

	private boolean flagSDCardMissing = false;
	
	public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        CB.dumpPhoneInfo(this);  							// debug info
        Logger.log(TAG + ".onCreate()");
     
        try
        {
	        setContentView(R.layout.main);       
        	
        	// make sure SD card is present
	        checkSDCard();
	        
	        // exit here if no SD card present ----------------------------
	        if(flagSDCardMissing) return; 

	        
	        // initialise media files and services        
	        Media.init();

	        
	        // initialise static User-ID 
	        // getLine1Number() et al. do not guarantee to return proper values.
	        // we therefore try the following:  1)Phone no 2)SIM no  3)Device id 
	        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
	        String uid = tm.getLine1Number();
	        if(uid == null || uid.trim().length() == 0) uid = tm.getSimSerialNumber();
	        if(uid == null || uid.trim().length() == 0) uid = tm.getDeviceId();
	        if(uid == null || uid.trim().length() == 0) uid = "unknown";
	        CB.API_UID = uid;
	        
	        
	        // initialise static TAG SETTINGS for this user
	        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
	        CB.INCLUDE_TAGS = preferences.getString(getString(R.string.setting_tags_include_key), "");
	        CB.EXCLUDE_TAGS = preferences.getString(getString(R.string.setting_tags_exclude_key), "");
	        CB.DEFAULT_TAGS = preferences.getString(getString(R.string.setting_tags_default_key), "");

	        
	        // is this a real start-up?
	        if(savedInstanceState == null)
	        {
	        	// DB.deleteDatabase(this);
		        // DB.generateLocalTestData(this);

		        // clear DB cache on start-up
		        DB.clearCache();
	        }

	        
	        // wire up UI
	        View btnAdd = this.findViewById(R.id.main_add);
	        btnAdd.setOnClickListener(this);
	        btnAdd.requestFocus();
	        View btnBrowse = this.findViewById(R.id.main_browse);
	        btnBrowse.setOnClickListener(this);
        }
        catch(Exception e)
        {
        	Logger.log(e);
        }
    }

	// ------------------------------------------
    // app becomes visible
	// ------------------------------------------
	public void onStart()
	{
		super.onStart();
        Logger.log(TAG + ".onStart()");    
        
        if(flagSDCardMissing)
        {
        	new AlertDialog.Builder(ActivityMain.this)
            .setMessage(R.string.welcome_alert_SD)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() 
            {
                    public void onClick(DialogInterface dialog, int whichButton) {finish();} 
            }).show();
        }
	}

	
	// ------------------------------------------
    // app becomes invisible
	// ------------------------------------------
	public void onStop()
	{
		super.onStop();
        Logger.log(TAG + ".onStop()");
	}

	
	// ------------------------------------------
    // interface OnClickListener
	// ------------------------------------------
    public void onClick(View v) 
    {
        Logger.log(TAG + ".onClick()");
    	
    	switch(v.getId())
    	{
    	case R.id.main_add: 
            try 
            {
            	Intent edit = new Intent(this, ActivityEdit.class);
            	startActivityForResult(edit, R.id.main_add);
            } 
            catch (Exception e) 
            {
                Logger.log(e);
            }
    		break;
    		
    	case R.id.main_browse: 
			
            try 
            {
        		Intent browse = new Intent(this, ActivityBrowse.class);
        		startActivity(browse);
            } 
            catch (Exception e) 
            {
                Logger.log(e);
            }
    		break;
    	}
    }
	

    
	
	// ------------------------------------------
    // callback for sub-activities
	// ------------------------------------------
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
         super.onActivityResult(requestCode, resultCode, data);

         Logger.log(TAG + ".onActivityResult()");
         Logger.log("requestCode", requestCode);
         Logger.log("resultCode", resultCode);
         
         switch(requestCode)
         {
         
         case R.id.main_add:

        	 if (resultCode == Activity.RESULT_OK) 
        	 {
    			try
    			{
	        		Intent browse = new Intent(this, ActivityBrowse.class);
	        		startActivity(browse);
    	        }
    	        catch(Exception e)
    	        {
    	        	Logger.log(e);
    	        }
        	 }
        	 break;
         }
    }

	
	// ------------------------------------------
    // We need a SD card to store image and audio files
    // If no SD card is present, notify user and exit.
	// ------------------------------------------
    private void checkSDCard()
    {
    	Logger.log(TAG + ".checkSDCard()");
    	
        if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) 
        {
        	flagSDCardMissing = true;
        	Logger.log("SD card missing");
        }
    }
    
    

	// ------------------------------------------
    // mww 06/2010 v.4 menu and preferences
    // create and listen to menu
	// ------------------------------------------
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.basic, menu);
		return true;
	}
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
		case R.id.mneSettings:
			 startActivity(new Intent(this, ActivitySettings.class));
			 return true;

		case R.id.mneAbout:
			 final TextView message = new TextView(this);
		     final SpannableString s = new SpannableString(getText(R.string.about_text));
			 Linkify.addLinks(s, Linkify.WEB_URLS);
			 message.setText(s);
			 message.setMovementMethod(LinkMovementMethod.getInstance());

			 new AlertDialog.Builder(this)
			 .setTitle(R.string.about_title)
			 .setIcon(R.drawable.icon)
			 .setPositiveButton("OK", null)
			 .setView(message)
			 .show();
        	 
			 return true;

		case R.id.mneHelp:
			 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(CB.getHelpPage(this)))); 
			 return true;
		}
		return false;
	}

}